<template>
  <div class="_components_image-text-material">
    <el-button v-if="isShow" v-show="bool" class="mb15" size="small" type="primary" @click="add({id: ''})">新增</el-button>
    <ul class="waterfall">
      <li v-for="item in list" :key="item.index" class="waterfall-item">
        <el-radio v-if="!bool" v-model="item.imgRadio" :label="1" @change="imgClick(item)">备选项</el-radio>
        <div class="img img1">
          <img :src="item.mpSourceNewsPageVos[0].thumbMediaUrl" alt="">
          <div class="div2 overflow1">{{ item.mpSourceNewsPageVos[0].title }}</div>
        </div>
        <div v-for="it in item.mpSourceNewsPageVos.slice(1)" :key="it.index" class="text-and-img">
          <span :title="it.title" class="overflow1">{{ it.title }}</span>
          <div class="img img2">
            <img :src="it.thumbMediaUrl" alt="">
          </div>
        </div>
        <div v-if="bool" class="btn">
          <el-button type="text" size="mini" @click="add(item)">编辑</el-button>
          <el-button v-if="item.asyncStatus === 0" type="text" size="mini" @click="uploadMediaSource(item.id)">同步</el-button>
          <el-dropdown style="margin: 0 0 0 10px" placement="bottom-start">
            <el-button type="text" size="mini">删除</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :disabled="item .asyncStatus === 0" @click.native="del(item.id, 0)">删除公众号</el-dropdown-item>
              <el-dropdown-item @click.native="del(item.id, 1)">删除全部</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </li>
    </ul>
    <vxe-pager
      :current-page.sync="params.pageNum"
      :page-size.sync="params.pageSize"
      :total="total"
      :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
      @page-change="getList()"
    />
    <el-dialog v-if="formVisible" :title="title" width="60%" :close-on-click-modal="false" :visible.sync="formVisible">
      <div class="text-img-dialog">
        <div class="text-img-dialog-left">
          <ul>
            <div :key="key">
              <li class="img img1" :class="{'active': active === 0}" @click="edit(0, addParams.params[0])">
                <img v-if="addParams.params[0].thumbMediaUrl" :src="addParams.params[0].thumbMediaUrl" alt="">
                <div v-else class="div1">缩略图</div>
                <div class="div2 overflow1">标题： {{ addParams.params[0].title }}</div>
              </li>
              <li v-for="(item, index) in addParams.params.slice(1)" :key="item.index" class="text-and-img" :class="{'active': active === index + 1}" @click="edit(index + 1, item)">
                <span :title="item.title" class="overflow1">{{ item.title }}</span>
                <!-- <i v-if="active === index + 1 && title === '新增'" @click.stop="delArr(index, item)">删除</i> -->
                <i v-if="active === index + 1" @click.stop="delArr(index, item)">删除</i>
                <div class="img img2">
                  <img v-if="item.thumbMediaUrl" :src="item.thumbMediaUrl" alt="">
                  <div v-else class="div1">缩略图</div>
                </div>
              </li>
              <!-- <li v-if="title === '新增'" style="cursor:pointer"> -->
              <li style="cursor:pointer">
                <i class="el-icon-plus" @click="addOne">新增</i>
              </li>
            </div>
          </ul>
        </div>
        <div class="text-img-dialog-right">
          <el-form ref="form" :model="dialogParams" :rules="rules" label-width="6rem">
            <el-row>
              <el-col :span="24">
                <el-form-item prop="title" label="标题：">
                  <el-input v-model="dialogParams.title" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="作者：">
                  <el-input v-model="dialogParams.author" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="原文地址：" prop="contentSourceUrl">
                  <el-input v-model="dialogParams.contentSourceUrl" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="thumbMediaId" label="素材图：">
                  <UserMessageReplyImg ref="chooseImg" :key="key1" :setinfo="setinfo" @getInfo="getInfo" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="图文摘要：" prop="digest">
                  <el-input v-model="dialogParams.digest" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="content" label="内容：">
                  <Tinymce ref="content" v-model="dialogParams.content" :tinymceinfo="tinymceinfo" @changeVal="changeTinymce" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item prop="showCoverPic" label="显示封面：">
                  <div>
                    <el-radio-group v-model="dialogParams.showCoverPic">
                      <el-radio label="0">不显示</el-radio>
                      <el-radio label="1">显示</el-radio>
                    </el-radio-group>
                  </div>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="24">
                <el-form-item label="打开评论">
                  <div>
                    <el-radio-group v-model="dialogParams.needOpenComment">
                      <el-radio label="0">不打开</el-radio>
                      <el-radio label="1">打开</el-radio>
                    </el-radio-group>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="粉丝评论">
                  <div>
                    <el-radio-group v-model="dialogParams.onlyFansCanComment">
                      <el-radio label="0">所有人评论</el-radio>
                      <el-radio label="1">粉丝评论</el-radio>
                    </el-radio-group>
                  </div>
                </el-form-item>
              </el-col> -->
            </el-row>
          </el-form>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveOne">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getLocalStorage } from '@/utils/localStorage'
import UserMessageReplyImg from './userMessageReply/img'
import Tinymce from '@/components/Tinymce'
import { addMediaSource, modifyMediaSource, listMediaSource, viewMediaSource, delMediaSource, uploadMediaSource } from '@/api/wxMp'
export default {
  components: { UserMessageReplyImg, Tinymce },
  props: {
    bool: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      tinymceinfo: {
        apppId: ''
      },
      key: 1,
      key1: 1,
      setinfo: {
        apppId: '',
        type: 'THUMB',
        asyncStatus: ''
      },
      flag: false,
      formVisible: false,
      title: '编辑',
      active: 0,
      addParams: {
        apppId: '',
        name: '1',
        sourceType: 'IMAGE_TEXT',
        params: []
      },
      dialogParams: {
        title: '',
        sort: '',
        thumbMediaId: '',
        thumbMediaUrl: '',
        author: '',
        digest: '',
        showCoverPic: '',
        content: '',
        contentSourceUrl: '',
        needOpenComment: '0',
        onlyFansCanComment: '1'
      },
      nullObj: {},
      rules: {
        title: [{ required: true, message: '请填写标题', trigger: 'blur' }],
        thumbMediaId: [{ required: true, message: '请选择素材', trigger: 'change' }],
        contentSourceUrl: [{ required: true, message: '请填写原文地址', trigger: 'blur' }],
        content: [{ required: true, message: '请填写内容', trigger: 'blur' }],
        digest: [{ required: true, message: '请填写图文摘要', trigger: 'blur' }],
        showCoverPic: [{ required: true, message: '请选择封面', trigger: 'change' }]
      },
      list: [],
      total: 0,
      isShow: false,
      params: {
        apppId: '',
        sourceType: 'IMAGE_TEXT',
        asyncStatus: '',
        name: '',
        pageNum: 1,
        pageSize: 20
      }
    }
  },
  watch: {
    formVisible(val) {
      if (!val) {
        this.dialogParams = {
          title: '',
          sort: '',
          thumbMediaId: '',
          thumbMediaUrl: '',
          author: '',
          digest: '',
          showCoverPic: '',
          content: '',
          contentSourceUrl: '',
          needOpenComment: '0',
          onlyFansCanComment: '1'
        }
        this.flag = false
        this.active = 0
        this.getList()
      }
    }
  },
  created() {
    this.setAppId(getLocalStorage('appIdSC'))
    this.nullObj = JSON.parse(JSON.stringify(this.dialogParams))
    this.getList()
  },
  methods: {
    imgClick(item) {
      if (item.imgRadio === 1) {
        this.$emit('imgBox', item)
      }
    },
    setAppId(info) {
      this.addParams.apppId = info.apppId
      this.params.apppId = info.apppId
      this.tinymceinfo.apppId = info.apppId
      this.setinfo.apppId = info.apppId
      this.params.name = info.name
      this.params.asyncStatus = info.asyncStatus
      this.key1++
    },
    changeTinymce(val) {
      this.dialogParams.content = val
      this.$refs.form.validateField('content')
    },
    edit(i, info, type = '') {
      if (type !== 1) {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.addParams.params[this.active] = JSON.parse(JSON.stringify(this.dialogParams))
            this.addParams.params.forEach((item, index) => {
              item.sort = index
            })
            const obj = JSON.parse(JSON.stringify(this.addParams))
            if (obj.id === '' || obj.id === undefined) {
              addMediaSource(this.addParams).then(res => {
                this.addParams.params[this.active] = JSON.parse(JSON.stringify(this.dialogParams))
                this.addParams.id = res
                this.key++
                this.$message.success('保存成功！')
                this.active = i
                this.dialogParams = JSON.parse(JSON.stringify(info))
                setTimeout(() => {
                  this.$refs.content.setContent(info.content)
                  this.$refs.chooseImg.path = info.thumbMediaUrl
                  this.$refs.form.clearValidate()
                }, 100)
              })
            } else {
              modifyMediaSource(this.addParams).then(res => {
                this.addParams.params[this.active] = JSON.parse(JSON.stringify(this.dialogParams))
                this.key++
                this.$message.success('保存成功！')
                this.active = i
                this.dialogParams = JSON.parse(JSON.stringify(info))
                setTimeout(() => {
                  this.$refs.content.setContent(info.content)
                  this.$refs.chooseImg.path = info.thumbMediaUrl
                  this.$refs.form.clearValidate()
                }, 100)
              })
            }
            this.flag = true
          }
        })
      } else {
        this.active = i
        this.dialogParams = JSON.parse(JSON.stringify(info))
        setTimeout(() => {
          this.$refs.content.setContent(info.content)
          this.$refs.chooseImg.path = info.thumbMediaUrl
          this.$refs.form.clearValidate()
        }, 100)
      }
    },
    delArr(i, info) {
      const obj = JSON.parse(JSON.stringify(this.addParams))
      obj.params.splice(i + 1, 1)
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // if (info.id === '') {
        //   this.$refs.content.setContent(this.addParams.params[0].content)
        //   this.$refs.chooseImg.path = this.addParams.params[0].thumbMediaUrl
        //   this.dialogParams = JSON.parse(JSON.stringify(this.addParams.params[0]))
        //   this.addParams.params.splice(i + 1, 1)
        //   this.active = 0
        //   this.flag = true
        //   this.$message.success('删除成功！')
        // } else {
        //   delImgTextOne({ id: info.id }).then(res => {
        modifyMediaSource(obj).then(res => {
          this.$refs.content.setContent(this.addParams.params[0].content)
          this.$refs.chooseImg.path = this.addParams.params[0].thumbMediaUrl
          this.dialogParams = JSON.parse(JSON.stringify(this.addParams.params[0]))
          this.addParams.params.splice(i + 1, 1)
          this.active = 0
          this.flag = true
          this.$message.success('删除成功！')
        })
        // }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    addOne() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.flag) {
            this.flag = false
            this.dialogParams = JSON.parse(JSON.stringify(this.nullObj))
            this.addParams.params.push(JSON.parse(JSON.stringify(this.nullObj)))
            this.$refs.content.setContent('')
            this.$refs.chooseImg.path = ''
            this.active++
          } else {
            this.$message.error('请先保存当前数据！')
          }
        }
      })
    },
    saveOne() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.addParams.params[this.active] = JSON.parse(JSON.stringify(this.dialogParams))
          this.addParams.params.forEach((item, index) => {
            item.sort = index
          })
          const obj = JSON.parse(JSON.stringify(this.addParams))
          if (obj.id === '' || obj.id === undefined) {
            addMediaSource(this.addParams).then(res => {
              this.addParams.params[this.active] = JSON.parse(JSON.stringify(this.dialogParams))
              this.addParams.id = res
              this.key++
              this.$message.success('保存成功！')
              this.formVisible = false
            })
          } else {
            modifyMediaSource(this.addParams).then(res => {
              this.addParams.params[this.active] = JSON.parse(JSON.stringify(this.dialogParams))
              this.key++
              this.$message.success('保存成功！')
              this.formVisible = false
            })
          }
          this.flag = true
        }
      })
    },
    getInfo(info) {
      this.dialogParams.thumbMediaId = info.id
      this.dialogParams.thumbMediaUrl = info.path
      this.$refs.form.clearValidate('thumbMediaId')
    },
    add(info) {
      this.title = info.id === '' ? '新增' : '编辑'
      if (info.id !== '') {
        viewMediaSource({ id: info.id }).then(res => {
          this.addParams = res
          this.formVisible = true
          this.flag = true
          this.edit(0, res.params[0], 1)
        })
      } else {
        this.addParams = {
          apppId: this.params.apppId,
          name: '1',
          sourceType: 'IMAGE_TEXT',
          params: []
        }
        this.addParams.params = []
        this.addParams.params.push(JSON.parse(JSON.stringify(this.dialogParams)))
        this.formVisible = true
        setTimeout(() => {
          this.$refs.content.setContent('')
        }, 100)
        setTimeout(() => {
          this.$refs.form.clearValidate('content')
        }, 100)
      }
    },
    del(id, type) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delMediaSource({ id, type }).then(res => {
          this.$message.success('删除成功！')
          this.getList()
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    getList() {
      this.setMpid(getLocalStorage('appIdSC'))
      this.isShow = getLocalStorage('appIdSC').asyncStatus === ''
      listMediaSource(this.params).then(res => {
        this.list = res.records
        this.total = res.total
        this.$nextTick(() => {
          this.list.forEach(el => {
            this.$set(el, 'imgRadio', 2)
          })
        })
      })
    },
    uploadMediaSource(id) {
      uploadMediaSource({ id }).then(res => {
        this.$message.success('同步成功！')
        this.getList()
      })
    }
  }
}
</script>

<style lang="scss">
._components_image-text-material {
  .img {
    position: relative;
    img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }
    .div1 {
      width: 100%;
      text-align: center;
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
    .div2 {
      width: 100%;
      padding: 0 10px;
      position: absolute;
      bottom: 0;
      left: 0;
      background-color: rgba(0,0,0,0.6);
      line-height: 28px;
      color: #fff;
      text-align: left;
    }
  }
  .img:before {
    content: "";
    display: block;
  }
  .img1 {
    width: 100%;
    margin-bottom: 5px;
  }
  .img2 {
    width: 20%;
  }
  .img1:before {
    padding-top: 50%;
  }
  .img2:before {
    padding-top: 100%;
  }
  .text-and-img{
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
    position: relative;
    padding: 0 10px;
    span {
      max-width: 78%;
    }
    >i {
      font-style: normal;
      position: absolute;
      cursor: pointer;
      padding: 5px 10px;
      right: 0;
      bottom: 0;
      background-color: #aaa;
      color: #fff;
      z-index: 1;
    }
  }
  .waterfall {
    width: 100%;
    column-gap:10px;
    column-count: 5;
    margin: 0 auto;
    .waterfall-item {
      padding: 10px;
      margin-bottom: 10px;
      break-inside: avoid;
      border: 1px solid #eaeaea;
      .btn {
        text-align: center;
      }
    }
  }
  @media (min-width: 992px) and (max-width: 1300px) {
    .waterfall {
      column-count: 3;
    }
    p {
      color:red;
    }
  }
  @media (min-width: 768px) and (max-width: 991px) {
    .waterfall {
      column-count: 2;
    }
    p {
      color: orange;
    }
  }
  @media (max-width: 767px) {
    .waterfall {
      column-count: 1;
    }
  }
  .text-img-dialog {
    display: flex;
    justify-content: space-between;
    .text-img-dialog-left {
      width: 30%;
      >ul {
        border: 1px solid #eee;
        li {
          padding: 10px;
          border: 2px solid #fff;
          border-bottom: 2px solid #eee;
        }
        li:last-child {
          border: 2px solid #fff;
          text-align: center;
        }
        .active {
          border: 2px solid skyblue !important;
        }
      }
    }
    .text-img-dialog-right {
      width: 68%;
    }
  }
}
</style>
